package org.example.zuul.web;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.example.zuul.filter.ZuulFilter;
import org.example.zuul.filter.ZuulProperties;
import org.example.zuul.http.RequestContext;
import org.example.zuul.http.ZuulServlet;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.ServletWrappingController;

@Component
public class ZuulController extends ServletWrappingController {
    private final ZuulProperties zuulProperties;

    public ZuulController(ZuulProperties zuulProperties) {
        this.zuulProperties = zuulProperties;
        setServletClass(ZuulServlet.class);
        setServletName("zuul");
        // Allow all
        setSupportedMethods((String[]) null);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Objects.requireNonNull(getServletContext()).setAttribute(ZuulFilter.ROUTES, zuulProperties.getRoutes().values());
        super.afterPropertiesSet();
    }

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            // We don't care about the other features of the base class, just want to
            // handle the request
            return super.handleRequestInternal(request, response);
        } finally {
            // @see com.netflix.zuul.context.ContextLifecycleFilter.doFilter
            RequestContext.getCurrentContext().unset();
        }
    }
}
